<template>
  <div class="my-level-page">
    <!-- 顶部导航栏 -->
    <van-nav-bar title="我的等级" left-arrow @click-left="onClickLeft" />

    <!-- 等级信息信息卡片 -->
    <div class="level-card">
      <div class="card-header">
        <!-- 显示用户头像 -->
        <img 
          class="avatar" 
          :src="userInfo.avatar || 'https://via.placeholder.com/40'" 
          alt="用户头像"
        >
        <div class="card-info">
          <p class="shop-name">{{ userInfo.username }}</p>
          <p class="level-name">{{ userInfo.membership_level || '普通会员' }}</p>
          <p class="discount-desc">商城购物可享 {{ userInfo.discount / 10 }} 折</p>
        </div>
      </div>
      <div class="progress-bar">
        <div class="progress" :style="{ width: progressWidth }"></div>
      </div>
      <div class="exp-and-level">
        <span class="exp-info">{{ userInfo.current_exp }} / {{ userInfo.total_exp }}</span>
        <div class="level-tag">V{{ userInfo.level }}</div>
      </div>
    </div>

    <!-- 成长特权 -->
    <div class="privilege-section">
      <div class="section-header">
        <h3 class="section-title">我的成长特权</h3>
        <van-button type="primary" class="upgrade-btn" @click="handleUpgrade">立即升级</van-button>
      </div>
      <van-grid :column-num="4" border="false">
        <van-grid-item icon="https://sparkshop.pfecms.com/static/images/discount.png" text="购物折扣" />
        <van-grid-item icon="https://sparkshop.pfecms.com/static/images/vip.png" text="专属徽章" />
        <van-grid-item icon="https://sparkshop.pfecms.com/static/images/experience.png" text="经验累积" />
        <van-grid-item icon="https://sparkshop.pfecms.com/static/images/experience.png" text="尊享客服" />
      </van-grid>
    </div>

    <!-- 会员等级体系 -->
    <div class="levels-list">
      <h3 class="section-title">会员等级体系</h3>
      <van-cell-group>
        <van-cell 
          v-for="level in levels" 
          :key="level.level"
          :title="`${level.name} (V${level.level})`"
          :label="`需消费${level.required_amount}元`"
          :value="level.is_current ? '当前等级' : ''"
        />
      </van-cell-group>
    </div>

    <!-- 快速升级技巧 -->
    <div class="tips-section">
      <h3 class="section-title">快速升级技巧</h3>
      <van-cell-group>
        <van-cell title="签到" :label="`每日签到可获得经验值`">
          <template #right-icon>
            <van-button type="info" size="small" class="action-btn">去签到</van-button>
          </template>
        </van-cell>
        <van-cell title="购买商品" :label="`购买商品可获得对应的经验值（+1点经验/元）`">
          <template #right-icon>
            <van-button type="info" size="small" class="action-btn">去购买</van-button>
          </template>
        </van-cell>
      </van-cell-group>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { NavBar, Grid, GridItem, Button, Cell, CellGroup, Toast } from 'vant';
import axios from 'axios';

export default {
  components: {
    NavBar,
    Grid,
    GridItem,
    Button,
    Cell,
    CellGroup
  },
  setup() {
    const router = useRouter();
    const userInfo = ref({
      username: '',
      membership_level: '',
      level: 0,
      current_exp: 0,
      total_exp: 0,
      discount: 0,
      avatar: ''  // 新增头像字段
    });
    const levels = ref([]);  // 存储所有会员等级

    const onClickLeft = () => {
      router.back();
    };

    // 获取会员信息
    const getMembershipInfo = async () => {
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          Toast('请先登录');
          router.push('/login');
          return;
        }
        // 确保token格式正确
        const headers = token.includes('Bearer ') 
          ? { 'Authorization': token } 
          : { 'Authorization': `Bearer ${token}` };
        
        const response = await axios.get('/user/membership_info', { headers });

        // 验证返回数据格式
        if (typeof (response.data) !== 'object' || Array.isArray(response.data)) {
          throw new Error('接口返回格式错误，预期JSON对象');
        }
        console.log('会员接口返回数据:', response.data);

        const data = response.data;
        const currentLevel = data.current_membership || {};
        
        // 筛选下一等级（比当前等级高的最小等级）
        const higherLevels = data.levels?.filter(level => level.level > currentLevel.level) || [];
        const nextLevel = higherLevels.length > 0 ? higherLevels[0] : currentLevel;

        // 更新用户信息
        userInfo.value = {
          username: data.username || '未知用户',
          membership_level: currentLevel.name || '普通会员',
          level: currentLevel.level || 0,
          current_exp: currentLevel.total_consumed || 0,
          total_exp: nextLevel.required_amount || currentLevel.total_consumed || 0,
          discount: currentLevel.discount || 100,
          avatar: data.avatar || ''  // 接收头像地址
        };

        // 存储所有等级信息
        levels.value = data.levels || [];

      } catch (error) {
        console.error('获取会员信息失败:', error);
        // 细化错误提示
        if (error.response?.status === 401) {
          Toast('登录已过期，请重新登录');
          localStorage.removeItem('token');
          setTimeout(() => router.push('/login'), 1500);
        } else if (error.message.includes('格式错误')) {
          Toast('数据格式异常，请联系管理员');
        } else {
          Toast(error.response?.data?.detail || '获取会员信息失败，请稍后重试');
        }
        // 错误状态下的默认值
        userInfo.value = {
          ...userInfo.value,
          username: '未知用户',
          membership_level: '普通会员',
          avatar: ''
        };
        levels.value = [];
      }
    };

    // 进度条计算（处理边界情况）
    const progressWidth = computed(() => {
      const { current_exp, total_exp, level } = userInfo.value;
      // 最高等级直接显示100%（假设最高等级为5）
      if (level >= 5) return '100%';
      // 避免除以0
      if (total_exp <= 0) return '0%';
      // 计算进度，最多100%
      const progress = Math.min((current_exp / total_exp) * 100, 100);
      return `${progress}%`;
    });

    onMounted(async () => {
      await getMembershipInfo();
    });

    const handleUpgrade = async () => {
      const token = localStorage.getItem('token');
      if (!token) {
        Toast('请先登录后再升级会员');
        setTimeout(() => router.push('/login'), 1500);
        return;
      }

      if (userInfo.value.level >= 5) {
        Toast('您已达最高会员等级');
        return;
      }

      // 跳转到超级会员页面
      router.push('/vip');
    };

    return {
      onClickLeft,
      progressWidth,
      userInfo,
      levels,  // 导出等级列表
      handleUpgrade
    };
  }
};
</script>
<style scoped>
/* 原有样式保持不变，新增头像样式 */
.my-level-page {
  background-color: #0b0b0d;
  min-height: 100vh;
  color: #fff;
}

/* 头像样式 */
.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
  object-fit: cover;
}

/* 移除原有circle样式（替换为头像） */
.circle {
  display: none;
}

/* 会员等级列表样式 */
.levels-list {
  margin: 15px;
}

/* 其他原有样式保持不变 */
.level-card {
  background: linear-gradient(to right, #bfa88f, #d8c6ac);
  margin: 15px;
  border-radius: 12px;
  padding: 15px;
  color: #000;
}

.card-header {
  display: flex;
  align-items: center;
}

.shop-name {
  font-size: 16px;
  font-weight: bold;
  margin: 0;
}

.discount-desc {
  font-size: 12px;
  margin: 2px 0 0 0;
}

.progress-bar {
  width: 100%;
  height: 6px;
  background-color: #999;
  border-radius: 3px;
  margin: 15px 0;
  overflow: hidden;
}

.progress {
  height: 100%;
  background-color: #000;
}

.exp-and-level {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.exp-info {
  font-size: 12px;
  color: #666;
}

.level-tag {
  background-color: #b08b61;
  padding: 4px 10px;
  border-radius: 15px;
  font-size: 12px;
}

.privilege-section {
  margin: 15px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin: 0;
}

.upgrade-btn {
  font-size: 12px;
  padding: 4px 12px;
}

.van-grid {
  background-color: #fff;
  border-radius: 8px;
  padding: 10px;
  color: #000;
}

.van-grid-item__text {
  font-size: 12px;
}

.tips-section {
  margin: 15px;
}

.van-cell-group {
  background-color: #fff;
  border-radius: 8px;
  color: #000;
}

.van-cell {
  font-size: 14px;
}

.action-btn {
  font-size: 12px;
  padding: 4px 12px;
}
</style>